package com.appspot.chooserepository.server;

import java.util.Date;
import java.util.List;

import com.appspot.chooserepository.client.RepositoryUserService;
import com.appspot.chooserepository.client.RepositoryUsers;
import com.appspot.chooserepository.shared.RepositoryUser;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RepositoryUserServiceImpl extends RemoteServiceServlet implements RepositoryUserService {

	public RepositoryUserServiceImpl() {
		super();
		LastChangedDate lastChangedDate = DataStoreUtils.queryLastChangedDate();
		if (lastChangedDate == null) {
			DataStoreUtils.storeLastChangedDate(new Date());
		}
	}

	@Override
	public RepositoryUsers getRepositoryUsersList() {
		RepositoryUsers repositoryUsers = null;
		try {
			LastChangedDate lastChangedDate = DataStoreUtils.queryLastChangedDate();
			List<RepositoryUserData> repositoryUserDataList = DataStoreUtils.queryRepositoriesUserData();
			if (lastChangedDate != null && repositoryUserDataList != null) {
				repositoryUsers  = new RepositoryUsers();
				for (RepositoryUserData repositoryUserData : repositoryUserDataList) {	
					RepositoryUser repositoryUser = repositoryUserData.getRepositoryUser();
					repositoryUsers.addRepositoryUser(repositoryUser);
				}
				repositoryUsers.setChangeDate(lastChangedDate.getLastChanged());	
			}
		} catch (Exception e) {

		}
		return repositoryUsers;	
	}

	@Override
	public Date updateRepositoryUsersList(RepositoryUsers repositoryUsers)  {
		Date result = null;
		try {
			LastChangedDate lastChangedDate = DataStoreUtils.queryLastChangedDate();
			if (lastChangedDate != null && repositoryUsers.isUpToDate(lastChangedDate.getLastChanged())) {
				DataStoreUtils.deleteRepositoriesUserData();
				for (int i = 0; i < repositoryUsers.size(); i++) {
					RepositoryUser repositoryUser = repositoryUsers.getRepositoryUser(i);
					RepositoryUserData repositoryUserData  = new RepositoryUserData(repositoryUser.getUser(),repositoryUser.getRepository(),repositoryUser.getLastUpdated());
					DataStoreUtils.storeRepositoryUserData(repositoryUserData);
				}
				result = new Date();
				DataStoreUtils.storeLastChangedDate(result);
			}
		} catch (Exception e) {
			
		}
		return result;
	}
		
}
